#!/bin/sh

. "$SPEC_PATH/abstract/dbops-restart"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/dbops-restart")"
}

e2e_test_install() {
  DBOPS_NAME="$(get_sgdbops_name restart)"

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1

  wait_pods_running "$CLUSTER_NAMESPACE" 1
}

e2e_test() {
  run_test "Checking that cluster restart fail when added invalid pgconf parameter" check_restart_cluster_fail
}

check_restart_cluster_fail() {
  if kubectl patch sgpgconfig -n "$CLUSTER_NAMESPACE" postgresconf --type json \
      -p '[{"op":"replace","path":"/spec/postgresql.conf/shared_preload_libraries","value":"pg_stat_statements, auto_explain, invalid-lib"}]' \
      >/dev/null 2>&1
    then
      success "sgpgconfig has been updated."
    else
      fail "sgpgconfig has not been updated."
  fi

  kubectl wait --timeout="$E2E_TIMEOUT"s sgcluster -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" --for=condition=PendingRestart

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  timeout: PT10S
  maxRetries: 0
  restart:
    method: InPlace
EOF

  if kubectl wait --timeout "${E2E_TIMEOUT}s" -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Completed \
    && kubectl wait --timeout "0s" -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Failed
  then
    success "The restart operation failed."
  else
    fail "The restart operation did not fail."
  fi

  if kubectl patch sgpgconfig -n "$CLUSTER_NAMESPACE" postgresconf --type json \
    -p '[{"op":"replace","path":"/spec/postgresql.conf/shared_preload_libraries","value":"pg_stat_statements, auto_explain"}]' \
    >/dev/null 2>&1
  then
    success "sgpgconfig has been updated."
  else
    fail "sgpgconfig has not been updated."
  fi

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME" > /dev/null 2>&1

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: restart
  restart:
    method: InPlace
EOF

  check_restart_ran_successfully  
}
